package com.jadows.tdog.server;

import com.google.common.util.concurrent.AbstractService;
import com.jadows.tdog.server.handler.ChatServerChannelHandler;
import com.jadows.tdog.server.handler.HttpHeadersHandler;
import com.jadows.tdog.server.option.ChatServerOption;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

import javax.annotation.Nonnull;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author taojiacheng
 */
public abstract class AbstractNettyChatServer extends AbstractService implements ChatServer {

    final ChatServerOption option;
    final ServerBootstrap bootstrap;
    final EventLoopGroup bossGroup;
    final EventLoopGroup workerGroup;

    final ExecutorService publicExecutor;

    public AbstractNettyChatServer(ChatServerOption option) {
        this.option = option;
        this.bootstrap = new ServerBootstrap();

        publicExecutor = new ScheduledThreadPoolExecutor(option.publicExecutorThread(), new DefaultThreadFactory("public-executor", true));
        bossGroup = new NioEventLoopGroup(option.parentGroupThread(), new DefaultThreadFactory("server-boss", true));
        workerGroup = new NioEventLoopGroup(option.workerGroupThread(), new DefaultThreadFactory("server-worker", true));
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // 服务端可连接队列
                .option(ChannelOption.SO_BACKLOG, 128)
                .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(@Nonnull SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        //30秒客户端没有向服务器发送心跳则关闭连接
                        pipeline.addLast("idle-handler", new IdleStateHandler(option.readerIdleTimeSeconds(), 0, 0));
                        // http 编解码
                        pipeline.addLast("http-codec", new HttpServerCodec());
                        // 支持大数据流
                        pipeline.addLast("chunk-write-handler", new ChunkedWriteHandler());
                        pipeline.addLast("http-aggregator", new HttpObjectAggregator(8192));
                        // ip 处理
                        pipeline.addLast("ip-handler", new HttpHeadersHandler());
                        // websocket 处理器
                        pipeline.addLast("ws-handler", new WebSocketServerProtocolHandler("/"));
                        // 业务逻辑处理器
                        pipeline.addLast("client-handler", new ChatServerChannelHandler(option.listener(), publicExecutor));
                    }
                });
    }

    @Override
    public ChatServerOption option() {
        return option;
    }


    @Override
    public ServerBootstrap bootstrap() {
        return bootstrap;
    }

    @Override
    public void start() {
        this.startAsync();
    }


    @Override
    public void shutdown() {
        this.stopAsync();
    }

}
